package org.example.JDBC;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:Lenovo
 * Date:2022-04-09
 * Time:14:36
 */
public class Insert {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        //设置数据库所在的地址
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/zyp?characterEncoding=utf8&useSSL=false");
        //设置登录数据库的用户名
        ((MysqlDataSource) dataSource).setUser("root");
        //设置登录数据库的密码
        ((MysqlDataSource) dataSource).setPassword("123456");
        //2.让代码和数据库服务器建立连接
        Connection connection = dataSource.getConnection();
        //3.用户输入插入的数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入id:");
        int ret1 = scanner.nextInt();
        System.out.println("请输入名字:");
        String str1 = scanner.next();
        //4.操作数据库
        String str = "insert into student1 values(?,?)";
        PreparedStatement statement = connection.prepareStatement(str);
        statement.setInt(1,ret1);
        statement.setString(2,str1);
        System.out.println("statement = " + statement);
        //5.执行sql
        int ret = statement.executeUpdate();
        System.out.println("ret = " + ret);
        //4.释放资源
        scanner.close();
        statement.close();
        connection.close();
    }
}
